package com.oop.example.gui;

import com.oop.example.work.bel.EntryHandler;
import com.oop.example.work.bel.Utils;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import javax.swing.JOptionPane;

/**
 *
 * @author -
 */
public class LabelDictionaryLoader extends javax.swing.JDialog {

    public LabelDictionaryLoader(Window parent) {
        super(parent, ModalityType.APPLICATION_MODAL);
        initComponents();
        jButtonAdd.addActionListener(new LoadDataListener());
        jButtonRW.addActionListener(new LoadDataListener());
        update();
    }

    private void update() {
        Properties props = Utils.getLabelDictionary();
        List<String> list = new ArrayList<String>();
        for (String str : props.stringPropertyNames()) {
            list.add(str);
        }
        Collections.sort(list);
        String d = "";
        for (String s : list) {
            d += s + " " + jTextFieldDelim.getText() + " " + props.getProperty(s) + Utils.NL;
        }
        jTextPaneCurrent.setText(d);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane1 = new javax.swing.JSplitPane();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextPaneData = new javax.swing.JTextPane();
        jLabelDelim = new javax.swing.JLabel();
        jTextFieldDelim = new javax.swing.JTextField();
        jButtonAdd = new javax.swing.JButton();
        jButtonRW = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextPaneCurrent = new javax.swing.JTextPane();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Загрузка новых данных"));

        jTextPaneData.setText("Скопируйте в текстовое поле словарь помет в следующем формате:\nав. – авиация\nавт.– автомобильное дело\nанат. – анатомия\nантр. – антропология\nархеол. – археология");
        jScrollPane1.setViewportView(jTextPaneData);

        jLabelDelim.setText("Разделитель");

        jTextFieldDelim.setText("=");

        jButtonAdd.setText("Добавить");

        jButtonRW.setText("Перезаписать");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabelDelim)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextFieldDelim, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButtonAdd)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonRW))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 369, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldDelim, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabelDelim)
                    .addComponent(jButtonAdd)
                    .addComponent(jButtonRW))
                .addContainerGap())
        );

        jSplitPane1.setLeftComponent(jPanel1);

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Уже загруженный справочник"));

        jTextPaneCurrent.setEditable(false);
        jScrollPane2.setViewportView(jTextPaneCurrent);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 305, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 398, Short.MAX_VALUE)
                .addContainerGap())
        );

        jSplitPane1.setRightComponent(jPanel2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSplitPane1)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSplitPane1)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAdd;
    private javax.swing.JButton jButtonRW;
    private javax.swing.JLabel jLabelDelim;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTextField jTextFieldDelim;
    private javax.swing.JTextPane jTextPaneCurrent;
    private javax.swing.JTextPane jTextPaneData;
    // End of variables declaration//GEN-END:variables

    private class LoadDataListener implements ActionListener {

        private Properties props;

        @Override
        public void actionPerformed(ActionEvent e) {
            if (e.getSource().equals(jButtonAdd)) {
                props = Utils.getLabelDictionary();
            } else {
                props = new Properties();
            }
            try {
                String delim = jTextFieldDelim.getText();
                String text = jTextPaneData.getText();
                String[] lines = text.split("\n");
                if (lines.length == 0) {
                    JOptionPane.showMessageDialog(LabelDictionaryLoader.this, "Не найдены данные для загрузки");
                    return;
                }
                for (String line : lines) {
                    String[] pair = line.split(delim);
                    if (pair.length == 2) {
                        props.setProperty(pair[0].trim(), pair[1].trim());
                    }
                }
                props.storeToXML(new FileOutputStream(new File(Utils.LabelDictionaryFile)), "", Utils.LabelDictionaryFileEncoding);
                JOptionPane.showMessageDialog(LabelDictionaryLoader.this, "В справочнике " + props.size() + " значение(й)");
            } catch (Exception ex) {
                ex.printStackTrace(System.out);
            }
            update();
        }
    }
}
